<?php namespace Admin\Model;

use Hdphp\Model\Model;

class Admin extends Model{

	//数据表
	protected $table = "shop_admin";

	//自动验证
	protected $validate=array(

	);

	// 模型中登录处理数据方法
	public function login()
	{
		if (isset($_POST['code']) && strtoupper($_POST['code']) != $_SESSION['code']) 
		{
			$this->error = '验证错误';
			return false;
		}
		if (empty($_POST['username'])) 
		{
			$this->error = '用户名不能为空';
			return false;
		}
		$user = $this->where('username',$_POST['username'])->first();
		if (!$user) 
		{
			$this->error = '帐号不存在';
			return false;
		}
		if ($user['password'] != md5($_POST['password'])) 
		{
			$this->error = '密码不正确';
			return false;
		}
		//压入data数组
		$data['admin_id'] = $user['admin_id'];
		$data['login_at'] = time();
		$data['login_ip'] = $_SERVER['REMOTE_ADDR'];
		//保存
		$this->save($data);
		//压入会话缓存中
		$_SESSION['admin_id']=$user['admin_id'];
        $_SESSION['username']=$user['username'];
        //返回真
        return true;
	}

	public function changePassword()
	{
		//判断字段不能为空
		$this->validate=array(
			array('password','required','密码不能为空',3,3),
            array('password','confirm:password_c','两次密码不一致',3,3),
            array('old_password','required','原密码不能为空',3,3),
		);
		//旧密码的判断
		$oldPwd = $this->where('admin_id',$_SESSION['admin_id'])->pluck('password');
		if (md5($_POST['old_password']) !== $oldPwd) 
		{
			$this->error = '原密码输入不正确';
			return false;
		}
		if ($this->create()) 
		{
			// 传参需要注意，把多余的字段unset掉
			$_POST['admin_id'] = $_SESSION['admin_id'];
			$_POST['password'] = md5($_POST['password']);
			unset($_POST['old_password']);
			unset($_POST['password_c']);
			return $this->save($_POST);
		}
	}

}